package com.mingserve.common.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * HTTP 工具类 用于发送HTTP请求
 *
 * @author lvwshuai
 * @date 2024-02-28
 */
public class HttpUtils
{
    /**
     * 发送 GET 请求
     *
     * @param url 请求的 URL
     * @return 请求响应的内容
     * @throws IOException 如果请求失败或发生其他 I/O 错误
     */
    public static String sendGet(String url) throws IOException
    {
        HttpURLConnection httpClient = (HttpURLConnection) new URL(url).openConnection();

        // 设置请求方式为 GET
        httpClient.setRequestMethod("GET");

        // 添加请求头
        httpClient.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = httpClient.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
            return readResponse(httpClient);
        } else {
            throw new IOException("GET请求失败：" + responseCode);
        }
    }

    /**
     * 发送 POST 请求
     *
     * @param url         请求的 URL
     * @param requestBody POST 请求的请求体
     * @return 请求响应的内容
     * @throws IOException 如果请求失败或发生其他 I/O 错误
     */
    public static String sendPost(String url, String requestBody) throws IOException
    {
        HttpURLConnection httpClient = (HttpURLConnection) new URL(url).openConnection();

        // 设置请求方式为 POST
        httpClient.setRequestMethod("POST");

        // 添加请求头
        httpClient.setRequestProperty("User-Agent", "Mozilla/5.0");
        httpClient.setRequestProperty("Content-Type", "application/json");

        // 启用输出流
        httpClient.setDoOutput(true);

        // 发送POST请求
        httpClient.getOutputStream().write(requestBody.getBytes("UTF-8"));

        int responseCode = httpClient.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
            return readResponse(httpClient);
        } else {
            throw new IOException("POST请求失败：" + responseCode);
        }
    }

    private static String readResponse(HttpURLConnection httpClient) throws IOException
    {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(httpClient.getInputStream()))) {
            StringBuilder response = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            return response.toString();
        }
    }
}
